package com.qfedu.microorder.recharge.service.impl;

import com.qfedu.common.pay.param.PayParam;
import com.qfedu.common.pay.service.PayService;

import com.qfedu.microorder.recharge.param.OrderPayParam;
import com.qfedu.microorder.recharge.service.OrderPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;

/**
 * @Classname OrderPayServiceImpl
 * @Description TODO
 * @Date 2025-06-03 11:48
 * @Created by 老任与码
 */
@Service
public class OrderPayServiceImpl implements OrderPayService {
    @Resource(name = "aliPayServiceImpl")
    private PayService aliPayService;

    // @Resource(name = "wxPayServiceImpl")


    @Override
    public String createOrderPay(OrderPayParam orderPayParam) {

        PayParam param = new PayParam();
        param.setOutTradeNo(orderPayParam.getOutTradeNo());
        param.setTotalAmount(new BigDecimal("0.01"));
        param.setSubject("充值订单");

        String qrUrl = null;
        Integer payPlatform = orderPayParam.getPayPlatform();
        if (payPlatform == 2) {
            qrUrl = aliPayService.createPay(param);
            System.out.println(qrUrl);
        } else if (payPlatform == 1) {
          //  qrUrl = wxPayService.createPay(param);
        }

        return qrUrl;
    }





    @Override
    public void notify(HttpServletRequest request, HttpServletResponse response) {
        // 区分支付宝或者微信的回调

        aliPayService.notify(request, response);

        //wxPayService.notify(request, response);
    }

    @Override
    public Integer checkOrderPayStatus(Integer payPlatform, String outTradeNo, Integer count) {
        try {
            payStatus(payPlatform, outTradeNo);
            return 1;
        } catch (Exception e) {
            if (count > 12) {
                // 达到最大轮询次数，关闭交易订单
                closePay(payPlatform, outTradeNo);
                return 2;
            } else {
                // 表示继续下次轮询
                return 3;
            }
        }
    }

    @Override
    public void returnNotify(HttpServletRequest request, HttpServletResponse response) {
        aliPayService.returnNotify(request, response);
    }


    private void payStatus(Integer payPlatform, String outTradeNo) {
        if (payPlatform == 1) {
            //wxPayService.payStatus(outTradeNo);
        } else if (payPlatform == 2) {
            aliPayService.payStatus(outTradeNo);
        }
    }

    private void closePay(Integer payPlatform, String outTradeNo) {
        if (payPlatform == 1) {
            //wxPayService.closePay(outTradeNo);
        } else if (payPlatform == 2) {
            aliPayService.closePay(outTradeNo);
        }
    }
}
